package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.pojo.Chance;
import com.ktjy.pojo.Dict;
import com.ktjy.pojo.SysRole;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.IChanceService;
import com.ktjy.service.IDictService;
import com.ktjy.service.ISysUserService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-01-15
 */
@Controller
@RequestMapping("/chance")
public class ChanceController {
    Logger logger = LoggerFactory.getLogger(ChanceController.class);

    @Autowired
    IChanceService iChanceService;
    @Autowired
    IDictService iDictService;
    @Autowired
    ISysUserService iSysUserService;

    @RequestMapping("/list")
    public String list(Chance chance,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       HttpSession session,
                       Model model) {
        try {
            //构造分页条件
            Page page = new Page(pageIndex, pageSize);
            //构造过滤条件
            QueryWrapper qw = new QueryWrapper();
            //只查询状态为未分配的
            qw.eq("chc_status", "1");
            if (chance.getChcCustName() != null && !chance.getChcCustName().equals("")) {
                qw.like("chc_cust_name", chance.getChcCustName());
            }
            if (chance.getChcTitle() != null && !chance.getChcTitle().equals("")) {
                qw.like("chc_title", chance.getChcTitle());
            }

            SysUser sysUser=(SysUser)session.getAttribute("loginUser");
            if(sysUser.getUsrRoleId()!=1){ //只查自己创建的数据
                qw.eq("chc_create_id",sysUser.getUsrId());
            }

            IPage<SysRole> pager = iChanceService.page(page, qw);
            model.addAttribute("pager", pager);

            //回显数据
            model.addAttribute("condition", chance);
        } catch (Exception e) {
            logger.error("ChanceController 中的 list 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "chance/list";
    }

    /**
     * 跳转到新增页面
     *
     * @return
     */
    @GetMapping("/add")
    public String add(Model model) {
        try {
            //查询客户等级
            QueryWrapper qw = new QueryWrapper();
            qw.eq("dict_type", "客户等级");
            List<Dict> levelList = iDictService.list(qw);
            model.addAttribute("levelList", levelList);

            //查询地区
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "地区");
            List<Dict> regionList = iDictService.list(qw2);
            model.addAttribute("regionList", regionList);

            //查询客户经理
            QueryWrapper qw3 = new QueryWrapper();
            qw3.eq("usr_role_id", 2);
            List<SysUser> userList = iSysUserService.list(qw3);
            model.addAttribute("userList", userList);

            return "chance/add";
        } catch (Exception e) {
            logger.error("ChanceController 中的 add 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增操作
     *
     * @param chance
     * @return
     */
    @PostMapping("/save")
    public String save(Chance chance, HttpSession session) {
        try {

            //获取当前登录用户
            SysUser loginUser = (SysUser) session.getAttribute("loginUser");
            chance.setChcCreateId(loginUser.getUsrId());
            chance.setChcCreateBy(loginUser.getUsrName());
            chance.setChcCreateDate(LocalDateTime.now());

            if (chance.getChcDueId() != null) {
                chance.setChcStatus("2");//已指派
                chance.setChcDueDate(LocalDateTime.now());
            } else {
                chance.setChcStatus("1");//未指派
            }
            boolean ok = iChanceService.save(chance);
            if (ok) {
                //跳转到列表;重定向到分页方法
                return "redirect:/chance/list";
            } else {
                //跳回新增页面
                return "chance/add";
            }
        } catch (Exception e) {
            logger.error("ChanceController 中的 save 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 跳转修改页面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/edit")
    public String edit(@RequestParam("id") Long id, Model model) {
        try {
            //1.根据id查询信息
            Chance chance = iChanceService.getById(id);
            model.addAttribute("chance", chance);
            //2.查询客户等级
            QueryWrapper qw = new QueryWrapper();
            qw.eq("dict_type", "客户等级");
            List<Dict> levelList = iDictService.list(qw);
            model.addAttribute("levelList", levelList);
            //3.查询地区
            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("dict_type", "地区");
            List<Dict> regionList = iDictService.list(qw2);
            model.addAttribute("regionList", regionList);
            //4.查询客户经理
            QueryWrapper qw3 = new QueryWrapper();
            qw3.eq("usr_role_id", 2);
            List<SysUser> userList = iSysUserService.list(qw3);
            model.addAttribute("userList", userList);
        } catch (Exception e) {
            logger.error("ChanceController 中的 edit 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "chance/edit";
    }

    @PostMapping("/update")
    public String update(Chance chance) {
        try {
            if (chance.getChcDueId() != null) {
                chance.setChcStatus("2");//已指派
                chance.setChcDueDate(LocalDateTime.now());
            } else {
                chance.setChcStatus("1");//未指派
            }
            boolean ok = iChanceService.updateById(chance);
            if (ok) {
                //跳转到列表;重定向到分页方法
                return "redirect:/chance/list";
            } else {
                //跳回新增页面
                return "chance/edit";
            }
        } catch (Exception e) {
            logger.error("ChanceController 中的 update 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Long id, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        try {
            //查询销售机会
            Chance chance = iChanceService.getById(id);
            //判断销售机会状态,是否为未分配
            if (!chance.getChcStatus().equals("1")) {
                map.put("delResult", -1);//销售机会不是未分配，不能删除
                return map;
            }
            //判断当前删除数据的人，是否为销售机会创建人
            SysUser loginUser = (SysUser) session.getAttribute("loginUser");
            if (!loginUser.getUsrId().equals(chance.getChcCreateId())) {
                map.put("delResult", -2);//删除人不是销售机会创建人，不允许删除
                return map;
            }
            boolean ok = iChanceService.removeById(id);  //调用service的方法进行数据删除
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            logger.error("ChanceController 中的 del 方法执行发生错误。", e);
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 跳转指派销售机会页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/assign")
    public String toAssign(Long id, Model model) {
        //1.查询客户经理
        QueryWrapper qw3 = new QueryWrapper();
        qw3.eq("usr_role_id", 2);
        List<SysUser> userList = iSysUserService.list(qw3);
        model.addAttribute("userList", userList);
        //2.根据销售机会ID，查询信息
        Chance chance = iChanceService.getById(id);
        model.addAttribute("chance", chance);

        return "chance/assign";
    }

    /**
     * 保存指派的信息
     * @param chance
     * @return
     */
    @PostMapping("/assign")
    public String assign(Chance chance) {
        try {
            chance.setChcDueDate(LocalDateTime.now());
            //修改销售机会的状态
            chance.setChcStatus("2");
            //修改销售机会的指派人员
            boolean ok = iChanceService.updateById(chance);
            if (ok) {
                //跳转到列表;重定向到分页方法
                return "redirect:/chance/list";
            } else {
                //跳回指派页面
                return "chance/assign";
            }
        } catch (Exception e) {
            logger.error("ChanceController 中的 assign 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }
}
